package com.gzz.common.tools;

import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.web.multipart.MultipartFile;

public class ExcelTool {
	public static <T> void export(String[] headers, List<T> list, HttpServletResponse response, Class<T> clazz) throws Exception {
		response.reset();
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition", "attachment;filename=test.xls");
		HSSFWorkbook workBook = new HSSFWorkbook();
		HSSFSheet sheet = workBook.createSheet("工资模板");
		int row = 0;
		Row rowm = sheet.createRow(row++);
		int column = 0;
		for (String head : headers) {
			rowm.createCell(column++).setCellValue(head);
		}
		Field fields[] = clazz.getDeclaredFields();
		for (T t : list) {
			rowm = sheet.createRow(row++);
			column = 0;
			for (Field field : fields) {
				field.setAccessible(true);
				Object value = field.get(t);
				rowm.createCell(column++).setCellValue(value.toString());
			}
		}
		OutputStream out = response.getOutputStream();
		workBook.write(out);
		out.flush();
		out.close();
		workBook.close();
	}

	public static <T> List<T> setList(final MultipartFile file, Class<T> cz) throws Exception {
		List<T> list = new ArrayList<>();
		HSSFWorkbook workBook = new HSSFWorkbook(file.getInputStream());
		HSSFSheet sheet = workBook.getSheetAt(0);
		Field fields[] = cz.getDeclaredFields();
		for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
			T t = cz.getDeclaredConstructor().newInstance();
			HSSFRow row = sheet.getRow(i);
			for (int j = 0; j < fields.length; j++) {
				HSSFCell cell = row.getCell(j);
				if (cell.getStringCellValue() != null) {
					fields[i].setAccessible(true);
					fields[i].set(t, cell.getStringCellValue());
				}
			}
			list.add(t);
		}
		if (workBook != null) {
			workBook.close();
		}
		return list;
	}

}
